//
//  KWMUserDao.m
//  IWant_User
//
//  Created by Yaotian on 12/26/14.
//  Copyright (c) 2014 kollway. All rights reserved.
//

#import "KWMUserDao.h"
#import "EGOCache.h"
#import "KWMAPIManager.h"
#import "KWMStringUtil.h"

static NSString *kwmKeySessionId = @"sessionId";
static NSString *kwmKeyUserPhone = @"userPhone";
static NSString *kwmKeyLockPassWord = @"lockPassWord";
static NSString *kwmKeySavedAccountPassword = @"savedAccountPassword";
static NSString *secretKey = @"!@#EQRGEQ$#Y%>O:";

@implementation KWMUserDao {
    EGOCache *myCache;
    KWMUser *current;
}

+ (KWMUserDao *)shareDao {
    static KWMUserDao *_userDao = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _userDao =[[self alloc] init];
        _userDao->myCache = [[EGOCache alloc]init];
        _userDao->myCache.defaultTimeoutInterval = 86400*30;//缓存有效期30天
    });
    return _userDao;
}


- (KWMUser *)loginUser {
    NSData *jsonData = [myCache dataForKey:NSStringFromClass([KWMUser class])];
    if (jsonData) {
        NSError *error;
        NSDictionary *userDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
        if (!error) {
            KWMUser *tmpUser = [[KWMUser alloc]initWithDictionary:userDict error:&error];
            if (!error && [tmpUser isValidated]) {
                current = tmpUser;
            }
        }
    }
    return current;
}


- (void)setLoginUser:(KWMUser *)user :(NSString *)sessionId{
    current = user;
    
    if (current == nil || ![current isValidated]) {
        [self deleteUser];
        [self deleteSession];
        [self unRegisterJpush];
    }else{
        [self setUserPhone:user.phone];
        [self saveUser:user];
        [self saveSession:sessionId];
        [self registerJpush];
    }
}

- (NSString *)sessionId {
    NSString *result = @"";
    NSString *fromCookieStore = @"";
    if ([KWMStringUtil isBlank:fromCookieStore]) {
        //从本地缓存拿sessionId
        NSString *fromLocalCache = [myCache stringForKey:kwmKeySessionId];
        if (![KWMStringUtil isBlank:fromLocalCache]) {
//            [KWMAPIManager sharedManager].sessionId = fromLocalCache;
            result = fromLocalCache;
        }
    }else{
        result = fromCookieStore;
    }
    return result;
}

- (void)setSessionId:(NSString *)sessionId {
    //sessionId存到本地缓存
    [myCache setString:sessionId forKey:kwmKeySessionId];
//    [KWMAPIManager sharedManager].sessionId = sessionId;
}


- (BOOL)isLogin {
    return ![KWMStringUtil isBlank:self.sessionId];
}

- (void)logout {
    self.sessionId = @"";
    [self deleteUser];
    [self unRegisterJpush];
}

- (void)saveUser:(KWMUser *)user {
    NSString *userJSON = user.toJSONString;
    [myCache setData:[userJSON dataUsingEncoding:NSUTF8StringEncoding] forKey:NSStringFromClass([KWMUser class])];
}
//
//- (void)saveDefaultAddress:(KWMUserAddress *)address {
//    KWMUser *loginUser = [self loginUser];
//    if (!loginUser) {
//        return  ;
//    }
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    [defaults setObject:address ? address.toJSONString : nil forKey:[NSString stringWithFormat:@"%@defaultAddress", loginUser.phone]];
//    [defaults synchronize];
//}
//
//- (KWMUserAddress *)defaultAddress {
//    KWMUser *loginUser = [self loginUser];
//    if (!loginUser) {
//        return nil;
//    }
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    NSString *addressString = [defaults objectForKey:[NSString stringWithFormat:@"%@defaultAddress", loginUser.phone]];
//    NSError *error;
//    KWMUserAddress *address = [[KWMUserAddress alloc] initWithString:addressString error:&error];
//    if (error) {
//        return nil;
//    }
//    return address;
//}

- (void)deleteUser {
    [myCache removeCacheForKey:NSStringFromClass([KWMUser class])];
}

//保存用户手机号码
-(void)setUserPhone:(NSString *)userPhone{
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setObject:userPhone forKey:@"LoginUserPhone"];
    [defaults synchronize];
}

//获取保存的用户号码
-(NSString *)userPhone{
    NSString *userPhone;
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    userPhone = [defaults objectForKey:@"LoginUserPhone"];
    return userPhone;
}

- (void)refresh {
}

- (void)deleteSession {
    
    self.sessionId = @"";
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setObject: self.sessionId forKey:kwmKeySessionId];
    [defaults synchronize];
}


- (void)saveSession:(NSString *)sessionId {
    if ([KWMStringUtil isEmpty:sessionId]) {
        //如果想清空sessionId的请调用deleteSession
        return;
    }
     self.sessionId = sessionId;
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setObject: self.sessionId forKey:kwmKeySessionId];
    [defaults synchronize];
}


#pragma mark JPush

-(void)registerJpush{
//    NSString *alias = [KWMStringUtil isBlank:self.loginUser.id]? @"" : [self.loginUser.id sam_MD5Digest];
//    NSString *tag = [KWMStringUtil isBlank:self.loginUser.companyId]? nil : [self.loginUser.companyId sam_MD5Digest];
//
//    NSSet *tags;
//    if (![KWMStringUtil isBlank:tag]) {
//        tags = [NSSet setWithArray:@[tag]];
//    }else{
//        tags = [NSSet setWithArray:@[]];
//    }
//    [APService setTags:tags alias:alias callbackSelector:@selector(registerCallbackJpushAlias:tags:alias:) object:self];
}

-(void)unRegisterJpush{
//    NSString *alias = @"";
//    NSSet *tags = [NSSet setWithArray:@[]];
//    [APService setTags:tags alias:alias callbackSelector:@selector(unRegisterCallbackJpushAlias:tags:alias:) object:self];
}

- (void)registerCallbackJpushAlias:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
    if(iResCode == 6002){//如果返回 6002 （超时）则建议重试
        [self registerJpush];
    }
}

- (void)unRegisterCallbackJpushAlias:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
    if(iResCode == 6002){//如果返回 6002 （超时）则建议重试
        [self unRegisterJpush];
    }
}





@end
